<template>

  <div v-if="loading"></div>
  <div v-else class="chart-container">
    <template v-if="data.length > 0">
      <div class="score-legend" v-if="isShowLegend">
        <div class="legend-item">
          <span class="dot green"></span>
          <span class="legend-text">90分以上</span>
        </div>
        <div class="legend-item">
          <span class="dot blue"></span>
          <span class="legend-text">80 - 90分</span>
        </div>
        <div class="legend-item">
          <span class="dot orange"></span>
          <span class="legend-text">60 - 80分</span>
        </div>
        <div class="legend-item">
          <span class="dot red"></span>
          <span class="legend-text">60分以下</span>
        </div>
      </div>
      <div ref="chartRef" class="chart-content"></div>
    </template>
    <chartEmpty v-else />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import chartEmpty from "./chartEmpty.vue";

const props = defineProps({
  data: {
    type: Array,
    default: () => [
      { name: "沟通能力", value: 95 },
      { name: "异议处理能力", value: 75 },
      { name: "客户关系建立能力", value: 64 },
      { name: "价值传递能力", value: 89 },
      { name: "需求挖掘能力", value: 40 }
    ]
  },
  unit: {
    type: String,
    default: "分"
  },
  nameMaxLength: {
    type: Number,
    default: 6
  },
  isShowLegend: {
    type: Boolean,
    default: true
  },
  loading: {
    type: Boolean,
    default: false
  }
});

const chartRef = ref(null);
let chart = null;

// 根据分数获取颜色
function getScoreColor(score) {
  if (score >= 90) return "#0FAD72";
  if (score >= 80) return "#436BFF";
  if (score >= 60) return "#FA8C16";
  return "#FF4D4F";
}

// 处理长文本
function formatLongText(text, maxLength) {
  if (!text) return "";
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength) + "...";
}

function initChart() {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  updateChart();
}

function updateChart() {
  console.log("updateChart: ", props.data);
  if (!chart) return;

  // 确保有数据时才更新图表
  if (!props.data || props.data.length === 0) {
    return;
  }

  const option = {
    grid: {
      containLabel: true
    },
    radar: {
      center: ["50%", "50%"],
      radius: "46%", // 稍微缩小一点以留出更多文字空间
      indicator: props.data.map((item) => ({
        name: `${formatLongText(item.name, props.nameMaxLength)}\n${item.value}${props.unit}`,
        max: 100,
        color: getScoreColor(item.value)
      })),
      splitNumber: 4,
      shape: "polygon",
      axisName: {
        color: (params) => params.value.color,
        fontSize: 12,
        padding: [0, 0],
        rich: {
          name: {
            fontSize: 12,
            lineHeight: 16,
            padding: [0, 0, 2, 0],
            width: 80, // 设置固定宽度
            align: "center" // 文字居中
          },
          value: {
            fontSize: 12,
            lineHeight: 14,
            padding: [0, 0],
            align: "center",
            fontWeight: 500,
            color: (params) => {
              // 从文本中提取分数
              const score = parseInt(params.value.split(props.unit)[0]);
              return getScoreColor(score);
            }
          }
        },
        formatter: (name) => {
          const parts = name.split("\n");
          if (parts.length > 1) {
            return `{name|${parts[0]}}\n{value|${parts[1]}}`;
          }
          return `{name|${name}}`;
        }
      },
      splitLine: {
        lineStyle: {
          color: "#E5E5E5"
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ["#FFFFFF", "#FAFAFA"]
        }
      },
      axisLine: {
        lineStyle: {
          color: "#E5E5E5"
        }
      }
    },
    series: [
      {
        type: "radar",
        data: [
          {
            value: props.data.map((item) => item.value), // 移除过滤条件，显示所有数据
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(22, 119, 255, 0.2)"
                },
                {
                  offset: 1,
                  color: "rgba(22, 119, 255, 0.1)"
                }
              ])
            },
            lineStyle: {
              color: "#1677FF",
              width: 2
            },
            label: {
              show: false // 隐藏数据点的标签，因为已经在标题中显示了
            },
            itemStyle: {
              color: (params) => getScoreColor(params.value),
              borderWidth: 2,
              borderColor: "#fff"
            },
            symbolSize: 6
          }
        ]
      }
    ]
  };

  chart.setOption(option);
}

// 监听数据变化
watch(
  () => props.data,
  () => {
    nextTick(() => {
      initChart();
    });
  },
  { deep: true }
);

// 使用防抖处理 resize
let resizeTimer = null;
const handleResize = () => {
  if (resizeTimer) clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    chart?.resize();
  }, 100);
};

window.addEventListener("resize", handleResize);

onMounted(() => {
  // 延迟初始化，确保DOM已完全渲染
  nextTick(() => {
    initChart();
  });
});

onUnmounted(() => {
  if (resizeTimer) clearTimeout(resizeTimer);
  chart?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style lang="less" scoped>
.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  overflow: hidden;

  .score-legend {
    display: flex;
    margin-bottom: 24px;
    padding: 0 4px;
    justify-content: space-between;
    //gap: 10px;
    width: 100%;

    .legend-item {
      display: flex;
      align-items: center;


      .dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 8px;
      }

      .legend-text {
        height: 20px;
        font-size: 12px;
        color: #8c8c8c;
        line-height: 20px;
      }

      .red {
        background-color: #ff4d4f;
      }

      .orange {
        background-color: #fa8c16;
      }

      .blue {
        background-color: #436bff;
      }

      .green {
        background-color: #52c41a;
      }
    }
  }
}

.chart-content {
  width: 100%;
  //height: 100%;
  height: 320px;
  max-width: 500px;
  aspect-ratio: 1;
}

/* 在小屏幕上自适应 */
@media screen and (max-width: 500px) {
  .chart-content {
    max-width: 100%;
    aspect-ratio: 1;
  }

  .chart-container {
    padding: 10px;
  }
}
</style>
